#{extends 'eventLayout.html' /}

<style>

    table {
        border-collapse: collapse;
        border-spacing: 0;
    }

    fieldset, img {
        border: 0;
    }

    address, caption, cite, code, dfn, em, strong, th, var {
        font-style: normal;
        font-weight: normal;
    }

    li {
        list-style: none;
    }

    caption, th {
        text-align: left;
    }

    q:before, q:after {
        content: '';
    }

    abbr, acronym {
        border: 0;
        font-variant: normal;
    }

    sup {
        vertical-align: text-top;
    }

    sub {
        vertical-align: text-bottom;
    }

    input, textarea, select {
        font-family: inherit;
        font-size: inherit;
        font-weight: inherit;
    }

    input, textarea, select {
        *font-size: 100%;
    }

    legend {
        color: #000;
    }
</style>

<link rel='stylesheet' type='text/css' href="@{'/public/css/jquery.weekcalendar.css'}"/>
<style>
    .ui-widget {
        font-size: 1em;
    }

    #event_edit_container, #about {
        display: none;
    }

    .wc-header td {
        /*	background: url(images/header-bg.png) repeat-x;*/
    }

    #event_edit_container label {
        display: block;
        margin-top: 1em;
        margin-bottom: 0.5em;
    }

    form ul {
        padding: 0.3em;
    }

    select, input[type='text'], textarea {
        width: 250px;
        padding: 3px;
    }

    input[type='text'] {
        width: 245px;
    }

    ul.formatted, ol.formatted {
        display: block;
        margin: 1em 0.5em;
    }

    ul.formatted li, ol.formatted li {
        margin: 5px 30px;
        display: auto;
    }

    ul.formatted li {
        list-style-type: disc;
    }

    ol.formatted li {
        list-style-type: decimal;
    }

    #switcher {
        float: left;
    }

</style>

<link rel='stylesheet' type='text/css' href="@{'/public/css/jwc_skins/default.css'}"/>


<!--
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'></script>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js'></script>
-->

*{#{set 'jqueryScripts'}}*
*{<script type='text/javascript' src="@{'/public/js/jquery-1.4.4.min.js'}"></script>}*
*{#{/set}}*

<script type='text/javascript' src="@{'/public/js/jquery.weekcalendar.js'}"></script>
<script type="text/javascript" src="@{'/public/js/date.js'}"></script>
<script>
    $(document).ready(function () {
//$('#switcher').themeswitcher();
    });
</script>
<script type='text/javascript'>
$(document).ready(function () {


    var $calendar = $('#calendar');
    var id = 10;

    $calendar.weekCalendar({
        "firstDayOfWeek":$.datepicker.regional['es'].firstDay,
        "shortDays":$.datepicker.regional['es'].dayNamesShort,
        "longDays":$.datepicker.regional['es'].dayNames,
        "shortMonths":$.datepicker.regional['es'].monthNamesShort,
        "longMonths":$.datepicker.regional['es'].monthNames,
        displayOddEven:true,
        timeslotsPerHour:4,
        allowCalEventOverlap:false,
        overlapEventsSeparate:true,
        firstDayOfWeek:1,
        businessHours:{start:8, end:18, limitDisplay:true },
        daysToShow:7,
        switchDisplay:{'1 dia':1, '3 dias sgt':3, 'dias habiles':5, 'semana':7},
        title:function (daysToShow) {
            return daysToShow == 1 ? '%date%' : '%start% - %end%';
        },
        height:function ($calendar) {
            return $(window).height() - $("h1").outerHeight() - 1;
        },
        eventRender:function (calEvent, $event) {
            if (calEvent.end.getTime() < new Date().getTime()) {
                $event.css("backgroundColor", "#aaa");
                $event.find(".wc-time").css({
                    "backgroundColor":"#999",
                    "border":"1px solid #888"
                });
            }
        },
        draggable:function (calEvent, $event) {
            return calEvent.readOnly != true;
        },
        resizable:function (calEvent, $event) {
            return calEvent.readOnly != true;
        },
        eventNew:function (calEvent, $event) {
            var $dialogContent = $("#event_edit_container");
            resetForm($dialogContent);
            var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
            var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
            var titleField = $dialogContent.find("input[name='title']");
            var bodyField = $dialogContent.find("textarea[name='body']");


            $dialogContent.dialog({
                modal:true,
                title:"Nueva ponencia",
                close:function () {
                    $dialogContent.dialog("destroy");
                    $dialogContent.hide();
                    $('#calendar').weekCalendar("removeUnsavedEvents");
                },
                buttons:{
                    save:function () {
                        calEvent.id = id;
                        id++;
                        calEvent.start = new Date(startField.val());
                        calEvent.end = new Date(endField.val());
                        calEvent.title = titleField.val();
                        calEvent.body = bodyField.val();

                        $.post('/${event.nick}/managePresentations/save',
                                {'presentationId':0,
                                    'start':calEvent.start.toISOString(),
                                    'end':calEvent.end.toISOString(),
                                    'title':calEvent.title,
                                    'description':calEvent.body },
                                function (data) {
                                    showStatus(data.isOk, data.message)
                                },
                                'json'
                        );

                        $calendar.weekCalendar("removeUnsavedEvents");
                        $calendar.weekCalendar("updateEvent", calEvent);
                        $dialogContent.dialog("close");

                    },
                    cancel:function () {
                        $dialogContent.dialog("close");
                    }
                }
            }).show();

            $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
            setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));

        },
        eventDrop:function (calEvent, $event) {
            $.post('/${event.nick}/managePresentations/save',
                    {'presentationId':calEvent.id,
                        'start':calEvent.start.toISOString(),
                        'end':calEvent.end.toISOString(),
                        'title':calEvent.title,
                        'description':calEvent.body },
                    function (data) {
                        showStatus(data.isOk, data.message)
                    },
                    'json'
            );
        },
        eventResize:function (calEvent, $event) {
            $.post('/${event.nick}/managePresentations/save',
                    {'presentationId':calEvent.id,
                        'start':calEvent.start.toISOString(),
                        'end':calEvent.end.toISOString(),
                        'title':calEvent.title,
                        'description':calEvent.body },
                    function (data) {
                        showStatus(data.isOk, data.message)
                    },
                    'json'
            );
        },
        eventClick:function (calEvent, $event) {

            if (calEvent.readOnly) {
                return;
            }

            var $dialogContent = $("#event_edit_container");
            resetForm($dialogContent);
            var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
            var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
            var titleField = $dialogContent.find("input[name='title']").val(calEvent.title);
            var bodyField = $dialogContent.find("textarea[name='body']");
            bodyField.val(calEvent.body);

            $dialogContent.dialog({
                modal:true,
                title:"Edit - " + calEvent.title,
                close:function () {
                    $dialogContent.dialog("destroy");
                    $dialogContent.hide();
                    $('#calendar').weekCalendar("removeUnsavedEvents");
                },
                buttons:{
                    save:function () {

                        calEvent.start = new Date(startField.val());
                        calEvent.end = new Date(endField.val());
                        calEvent.title = titleField.val();
                        calEvent.body = bodyField.val();

                        $calendar.weekCalendar("updateEvent", calEvent);
                        $.post('/${event.nick}/managePresentations/save',
                                {'presentationId':calEvent.id,
                                    'start':calEvent.start.toISOString(),
                                    'end':calEvent.end.toISOString(),
                                    'title':calEvent.title,
                                    'description':calEvent.body },
                                function (data) {
                                    showStatus(data.isOk, data.message)
                                },
                                'json'
                        );
                        $dialogContent.dialog("close");
                    },
                    "delete":function () {
                        $calendar.weekCalendar("removeEvent", calEvent.id);
                        $dialogContent.dialog("close");
                    },
                    cancel:function () {
                        $dialogContent.dialog("close");
                    }
                }
            }).show();

            var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
            var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
            $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
            setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
            $(window).resize().resize(); //fixes a bug in modal overlay size ??

        },
        eventMouseover:function (calEvent, $event) {
        },
        eventMouseout:function (calEvent, $event) {
        },
        noEvents:function () {

        },
        data:function (start, end, callback) {
            var eventData = getEventData();
            callback(eventData);
        }
    });

    function resetForm($dialogContent) {
        $dialogContent.find("input").val("");
        $dialogContent.find("textarea").val("");
    }

    function getEventData() {
        var year = new Date().getFullYear();
        var month = new Date().getMonth();
        var day = new Date().getDate();

        return {
            events:[
            #{list items:event.presentations, as:'presentation'}
                {
                    "id":'${presentation.id}',
                    "start":Date.parse('${presentation.dateBegin.format("yyyy-MM-dd HH:mm:ss")}', "yyyyMMddhhmmss"),
                    "end":Date.parse('${presentation.dateEnd.format("yyyy-MM-dd HH:mm:ss")}', "yyyyMMddhhmmss"),
                    "title":'${presentation.name}',
                    "description":'${presentation.description}'
                }
            ${presentation_isLast ? '' : ','}
            #{/list}
            ]
        };
    }


    /*
    * Sets up the start and end time fields in the calendar event
    * form for editing based on the calendar event being edited
    */
    function setupStartAndEndTimeFields($startTimeField, $endTimeField, calEvent, timeslotTimes) {

        $startTimeField.empty();
        $endTimeField.empty();

        for (var i = 0; i < timeslotTimes.length; i++) {
            var startTime = timeslotTimes[i].start;
            var endTime = timeslotTimes[i].end;
            var startSelected = "";
            if (startTime.getTime() === calEvent.start.getTime()) {
                startSelected = "selected=\"selected\"";
            }
            var endSelected = "";
            if (endTime.getTime() === calEvent.end.getTime()) {
                endSelected = "selected=\"selected\"";
            }
            $startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
            $endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");

            $timestampsOfOptions.start[timeslotTimes[i].startFormatted] = startTime.getTime();
            $timestampsOfOptions.end[timeslotTimes[i].endFormatted] = endTime.getTime();

        }
        $endTimeOptions = $endTimeField.find("option");
        $startTimeField.trigger("change");
    }

    var $endTimeField = $("select[name='end']");
    var $endTimeOptions = $endTimeField.find("option");
    var $timestampsOfOptions = {start:[], end:[]};

    //reduces the end time options to be only after the start time options.
    $("select[name='start']").change(function () {
        var startTime = $timestampsOfOptions.start[$(this).find(":selected").text()];
        var currentEndTime = $endTimeField.find("option:selected").val();
        $endTimeField.html(
                $endTimeOptions.filter(function () {
                    return startTime < $timestampsOfOptions.end[$(this).text()];
                })
        );

        var endTimeSelected = false;
        $endTimeField.find("option").each(function () {
            if ($(this).val() === currentEndTime) {
                $(this).attr("selected", "selected");
                endTimeSelected = true;
                return false;
            }
        });

        if (!endTimeSelected) {
            //automatically select an end date 2 slots away.
            $endTimeField.find("option:eq(1)").attr("selected", "selected");
        }

    });

});
</script>
<br/>
<div id='calendar'></div>
<div id="event_edit_container">
    <form>
        <input type="hidden"/>
        <ul>
            <li>
                <span>Fecha: </span><span class="date_holder"></span>
            </li>
            <li>
                <label for="start">Empieza: </label><select name="start">
                <option id="start" value="">Select Start Time</option>
            </select>
            </li>
            <li>
                <label for="end">Termina: </label><select name="end">
                <option id="end" value="">Select End Time</option>
            </select>
            </li>
            <li>
                <label for="title">Nombre: </label><input id="title" type="text" name="title"/>
            </li>
            <li>
                <label for="body">Descripción: </label><textarea id="body" name="body"></textarea>
            </li>
        </ul>
    </form>
</div>
